﻿using SHFK.B2C.YouZanYun.Network;
using SHKF.B2C.Model;
using SHKF.B2C.YouZanYun.Model.Dto.Token;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace SHKF.B2C.YouZanYun.Consumer
{
    public class HttpClientYouZanYun : HttpClientYzy
    { 
        //----------------------------------------Erp
        private string urlErpGetToken = "/Token"; 
        private string urlErpSaveToken = "/Token/Save";

        private string urlDb;
        public HttpClientYouZanYun(string urlDb)
        {
            base.BaseAddress = new Uri("https://open.youzanyun.com");
            this.urlDb = urlDb;
        }

        protected async override Task<TokenYZYDto> GetToken()
        {　
            TokenYZYDto requestToken = null;
            DateTime now = DateTime.Now;
            long timestamp = DateTimeUtil.DateTimeToLongTimeStamp(now.AddHours(1)); //一小时误差

            try
            {
                //数据库存在
                requestToken = await this.GetErpToken();

                if (requestToken == null)
                {
                    requestToken = await GetYouZanYunToken(false);
                    if (requestToken.code == 200)
                    {
                        await this.SaveErpToken(requestToken);
                    }
                }
                else
                {
                    if (requestToken.Data != null && requestToken.Data.expires <= timestamp) //如果access_token过期
                    {
                        //刷新    
                        //if (requestToken.Data.re_expires <= timestamp) //如果刷新时间也过期了,需要重新申请店铺，这是极端事件，需要手动去有赞云
                        //{
                        //    requestToken = await GetYouZanYunToken(false);
                        //    if (requestToken.code > 0)
                        //    {
                        //        requestToken = null;
                        //        this.access_token = "";

                        //        throw new Exception("refresh_expires:如果刷新refresh_expires也过期了,需要重新申请店铺，这是极端事件，需要手动去有赞云的平台操作");
                        //    }
                        //}
                        //else //如果refresh_token没有过期，重新刷新
                        //{
                        requestToken = await GetYouZanYunToken(true);
                        //}
                    }
                    else
                    {
                        requestToken.code = 200;
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            return requestToken;
        }
 
        private async Task<TokenYZYDto> GetErpToken()
        {
            TokenYZYDto dto = null;
            TokenDataDto requestTokenDto = null;
            try
            {
                HttpResponseMessage httpResponseMessage = await base.GetAsync(this.urlDb + this.urlErpGetToken + $"?authority_id={authority_id}");
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    requestTokenDto = await httpResponseMessage.Content.ReadAsAsync<TokenDataDto>();
                    if (string.IsNullOrEmpty(requestTokenDto.access_token)
                        || string.IsNullOrEmpty(requestTokenDto.authority_id))
                    {

                    }
                    else
                    {
                        dto = new TokenYZYDto();
                        dto.message = "";
                        dto.code = 0;
                        dto.Data = requestTokenDto;

                        this.access_token = requestTokenDto.access_token;
                    }
                }
            }
            catch (Exception ex)
            {
                dto = new TokenYZYDto();
                dto.message = ex.Message;
                dto.code = -1;
            }

            return dto;
        }

        private async Task<TokenYZYDto> SaveErpToken(TokenYZYDto requestTokenDto)
        {
            try
            {
                //用本地时间计算过期时间
                DateTime now = DateTime.Now;
                TokenDataDto data = requestTokenDto.Data;
                //data.expires = DateTimeUtil.DateTimeToTimeStamp(now.AddDays(7));
                data.re_expires = DateTimeUtil.DateTimeToLongTimeStamp(now.AddDays(28));

                var paras = new List<KeyValuePair<string, string>>();
                paras.Add(new KeyValuePair<string, string>("access_token", data.access_token));
                paras.Add(new KeyValuePair<string, string>("expires", data.expires.ToString()));
                paras.Add(new KeyValuePair<string, string>("refresh_token", data.refresh_token));
                paras.Add(new KeyValuePair<string, string>("re_expires", data.re_expires.ToString()));
                paras.Add(new KeyValuePair<string, string>("scope", data.scope));
                paras.Add(new KeyValuePair<string, string>("authority_id", this.authority_id));

                var content = new FormUrlEncodedContent(paras);
                HttpResponseMessage httpResponseMessage = await base.PostAsync(this.urlDb + this.urlErpSaveToken, content);
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    requestTokenDto = await httpResponseMessage.Content.ReadAsAsync<TokenYZYDto>();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return requestTokenDto;
        }


    }
}
